package com.example.guardian.client.task;

import com.example.guardian.client.kafka.KafkaProducerService;
import com.example.guardian.client.manager.TransactionMessageManager;
import com.example.guardian.client.message.model.MessageModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * 事务消息发送
 *
 * @author gang.wang 2021/12/9
 */
@Component
@EnableScheduling
public class TransactionMessageSendTask {

    @Autowired
    private TransactionMessageManager transactionMessageManager;
    @Autowired
    private KafkaProducerService kafkaProducerService;

    @Scheduled(cron = "0/50 * * * * ?")
    public void transactionCallback(){

        List<MessageModel> messageModels = transactionMessageManager.listMessageSend();
        if (CollectionUtils.isEmpty(messageModels)) {
            return;
        }

        for (MessageModel messageModel : messageModels) {
            try {
                kafkaProducerService.sendMessageSync(messageModel.getTopic(), messageModel.getJsonMessageInfo());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
